package basic;

import org.junit.Test;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author： pang-yun
 * @date： 2021-08-30 13:30
 * 功能目的 ：用于  分散与集中
 */

public class DisperseAndConcentrate {
    @Test
    public void concentrate(){
        ByteBuffer disperse = StandardCharsets.UTF_8.encode("Disperse ");
        ByteBuffer concentrate = StandardCharsets.UTF_8.encode(" Concentrate ");
        ByteBuffer elephant = StandardCharsets.UTF_8.encode(" elephant");

        try (FileChannel rw = new RandomAccessFile("G:\\MyProgran\\play\\Netty-demo\\src\\main\\resources\\to.txt", "rw").getChannel()) {
            rw.write(new ByteBuffer[]{disperse,concentrate,elephant});
        } catch (IOException e) {
        }
    }




    @Test
    public void disperse() {
        try (FileChannel rw = new RandomAccessFile("G:\\MyProgran\\play\\Netty-demo\\src\\main\\resources\\ScatteringReading.txt", "r").getChannel()) {
            ByteBuffer allocate = ByteBuffer.allocate(5);
            ByteBuffer allocate1 = ByteBuffer.allocate(5);
            ByteBuffer allocate2 = ByteBuffer.allocate(5);
            ByteBuffer allocate3 = ByteBuffer.allocate(5);

            rw.read(new ByteBuffer[]{allocate1, allocate2, allocate3, allocate});

            read(allocate1);
            read(allocate2);
            read(allocate3);
            read(allocate);
        } catch (IOException e) {
        }

    }

    public static void read(ByteBuffer buffer) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            System.out.print(String.valueOf((char) b));
        }
    }
}
